package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/setmeal")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/upload")
    @ApiOperation("文件上传接口")
    public Result<String> upload (@RequestParam MultipartFile file) {
        log.info("文件上传: {}",file);

        try {
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
            String filePath = aliOssUtil.upload(file.getBytes(), fileName);
            log.info(filePath);
            //向redis中保存数据
            String key = "picture";
            SetOperations redis = redisTemplate.opsForSet();
            redis.add(key,filePath);

            return Result.success(filePath);
        } catch (Exception e) {
            log.info("文件上传失败:{}",e);
        }
        return Result.error(MessageConstant.PIC_UPLOAD_FAIL);
    }
}
